package com.cloudlibrary.controller;

import com.cloudlibrary.domain.User;
import com.cloudlibrary.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Autowired
    private UserServiceImpl userService;

    /*登录*/
    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request) {
        User u = userService.login(user);
        if (u != null) {
            HttpSession session = request.getSession();
            session.setAttribute("username", u.getName());
            session.setAttribute("USER_SESSION",u);
            //session设置为永久
            session.setMaxInactiveInterval(-1);
            /*重定向*/
            return "redirect:/admin/main.jsp";
        }
        request.setAttribute("msg", "用户名或密码错误");
        return "forward:/admin/login.jsp";
    }

    /*注销*/
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            session.invalidate();//销毁Session
            return "forward:/admin/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "系统错误");
            return "forward:/admin/login.jsp";
        }
    }


}
